<template>
  <div class="crud-opts">
    <span class="crud-flex" style="display:flex;align:center">
      <slot name="left"/>
      <el-button class="btn-height" icon="el-icon-plus" v-if="crud.optShow.add"
                 v-permission="permission.add==undefined ? ['']:permission.add" @click="crud.toAdd"
                 style="border-radius: 0;color:white;margin-right:10px;background:#347DE1 !important"></el-button>
      <img class="img" src="@images/update.png" alt="" @click="doReply()">
      <!--更多操作-->
      <el-popover v-if="checkPermission(['appGroup:edit', 'appGroup:del', 'appGroup:refresh'])"
                  placement="bottom" width="100" trigger="click" style="height:30px">
        <img class="img" slot="reference" src="@images/more.png" alt="">
        <div>
          <el-row>
            <el-button v-permission="permission.edit==undefined ? ['']:permission.edit"
                       type="text"
                       @click="crud.toEdit(crud.selections[0])" :disabled="crud.selections.length !== 1">修改</el-button>
          </el-row>
          <el-row>
            <el-button v-permission="permission.del==undefined ? ['']:permission.del"
                       :disabled="crud.selections.length == 0"
                       type="text" :loading="crud.delAllLoading"
                       @click="toDelete(crud.selections)">删除</el-button>
          </el-row>
          <el-row>
            <el-button v-permission="permission.refresh==undefined ? ['']:permission.refresh"
                       :disabled="crud.selections.length !== 1" type="text" :loading="crud.delAllLoading"
                       @click="toRefreshThread(crud.selections[0])">刷新线程组</el-button>
          </el-row>
        </div>
      </el-popover>
      <el-popover placement="bottom-end" width="150" style="height:30px" trigger="click">
        <img class="img" slot="reference" src="@images/gezi.png" alt="">
        <el-checkbox v-model="allColumnsSelected" :indeterminate="allColumnsSelectedIndeterminate"
                     @change="handleCheckAllChange">
          全选
        </el-checkbox>
        <el-checkbox
          v-for="item in crud.props.tableColumns"
          :key="item.label"
          v-model="item.visible"
          @change="handleCheckedTableColumnsChange(item)"
        >
          {{ item.label }}
        </el-checkbox>
      </el-popover>
      <el-button-group v-if="crud.queryList.length > 0" style="height:30px">
        <img class="img" src="@images/search.png" @click="toggleSearch()" v-if="crud.props.searchToggle"
             alt="">
        <div style="display: inline-block;display:flex;align:center" class="select">
          <img class="img" style="margin-right:0px !important" v-if="!crud.props.searchToggle"
               src="@images/hidden.png" alt="" @click="toggleSearch()">
          <el-input placeholder="请输入内容" v-model="qryParam" style="width: 400px;"
                    class="input-with-select" @change="paramChange" v-if="!crud.props.searchToggle" clearable>
            <el-select v-model="qryCloum" @change="cloumChange" slot="prepend" filterable placeholder="请选择"
                       style="width: 130px">
              <el-option v-for="(item,i) in crud.queryList" :key="i" :label="item.cloumName"
                         :value="item.cloumValue"></el-option>
            </el-select>
          </el-input>
          <img class="img" v-if="!crud.props.searchToggle" slot="append" src="@images/search.png" alt=""
               @click="doQuery">
        </div>
      </el-button-group>
      <!--右侧-->
      <slot name="right"/>
    </span>
    <el-button-group class="crud-opts-right">
      <el-pagination :page-size.sync="page.size"
                     :total="page.total"
                     :current-page.sync="page.page"
                     :pager-count="5" prev-text=" " next-text=" "
                     style="margin-top: 8px;"
                     layout="prev, pager, next,sizes,total"
                     @size-change="crud.sizeChangeHandler($event)"
                     @current-change="crud.pageChangeHandler"

      />
    </el-button-group>
  </div>
</template>
<script>
import CRUD, {crud, pagination} from '@crud/crud'
import appGroup from '@/api/app/appGroup'
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  mixins: [crud(), pagination()],
  props: {
    permission: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      qryParam: '',
      qryCloum: ''
    }
  },
  created() {
    this.crud.updateProp('searchToggle', true)
  },
  methods: {
    checkPermission,
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        if (datas instanceof Array && datas.length > 0) {
          //删除的两种类型  pkId(常用删除)和id(用户sys_user删除)
          if (datas[0].hasOwnProperty('id')) {
            this.crud.doDelete(datas)
          } else {
            this.crud.doDeleteByPkId(datas)
          }
        }
      }).catch(() => {
      })
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.$message({
          message: '请至少选择一列',
          type: 'warning'
        });
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function () {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
      if (this.crud.props.searchToggle) {
        delete this.crud.query[this.qryCloum];
      }
    },
    paramChange(value) {
      this.qryParam = value;
    },
    cloumChange(value) {
      this.qryCloum = value;
      for (let key in this.crud.query) {
        if (key != this.qryCloum) {
          delete this.crud.query[key]
        }
      }
    },
    doReply() {
      this.crud.findVM('presenter').$refs['table'].clearFilter()
      this.crud.query = {}
      this.qryParam = ''
      this.qryCloum = ''
      this.crud.page.page = 1;
      this.crud.params = {};
      this.crud.toQuery()
    },
    doQuery() {
      var key = "";
      var value = "";
      if (this.qryCloum == null || this.qryCloum == '') {
        this.$message({
          message: '请先选择搜索项',
          type: 'warning'
        });
        return;
      }
      if (this.qryCloum != null && this.qryCloum != '') {
        key = this.qryCloum;
      }
      if (this.qryParam != '' && this.qryParam != null) {
        value = this.qryParam;
      }
      this.crud.query[key] = value;
      this.crud.toQuery();
    },
    toRefreshThread(data) {
      appGroup.refreshGroup(data).then(res => {
        if (res) {
          this.$notify({
            title: '成功',
            message: '刷新线程成功!',
            type: 'success'
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: '刷新线程异常!'
          });
        }
      })
    }
  }
}
</script>

<style>
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}
</style>
